#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QtGui>
#include <QMessageBox>

#include "producttypes.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{


    ui->setupUi(this);

    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(dbReader.getDbServer());
    db.setPassword(dbReader.getDbPassword());
    db.setDatabaseName(dbReader.getDbName());
    db.setUserName(dbReader.getDbUserName());

    if (db.open())
        {
        LoadStockList();
        }
    else
        {
        QMessageBox::warning(this, "Error", tr("DB not openn\n <b>%1</b>").arg(db.lastError().text()));
        }

    QSplitter *mainSplit = new QSplitter(this);
    mainSplit->addWidget(ui->lstLeftBar);
    mainSplit->addWidget(ui->mainPanel);

    this->setCentralWidget(mainSplit);

    connect(ui->lstLeftBar, SIGNAL(currentRowChanged(int)), ui->mainPanel, SLOT(setCurrentIndex(int)));

    ui->lstLeftBar->resize(10, 1000);
}

void MainWindow::LoadStockList()
{
    if (db.isOpen())
        {
        QSqlQueryModel *model = new QSqlQueryModel(ui->treeView);
        model->setQuery("SELECT * FROM stock");
        ui->treeView->setModel(model);
        }
    else
        {
        QMessageBox::warning(this, "Error", "DB not open");
        }
}

MainWindow::~MainWindow()
{
    //db.close();
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::on_cboStyles_currentIndexChanged(QString )
{
    QApplication::setStyle(ui->cboStyles->currentText());
}


void MainWindow::on_pushButton_3_clicked()
{
    ProductTypes *prod = new ProductTypes();
    prod->setDb(db);
    prod->show();
}
